import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;


public class me4k extends Applet implements ActionListener, KeyListener {
	
	//Ratio of screen to inner square
	final int innerRatio = 3;

	//movement speed
	final int moveSpeed = 5;
	
	//variables for screen size+inner square
	int width,height,iWidth,iHeight;
	
	int x=0,y=0;
	
	@Override
	public void init()
	{
		//Setup height and widths
		width = getWidth();
		height = getHeight();
		iWidth = width/innerRatio;
		iHeight = height/innerRatio;
		this.addKeyListener( this );
		x = width/2;
		y = height/2;
	}
	
	@Override
	public void start()
	{
		
	}
	
	@Override
	public void stop()
	{
		
	}
	
	@Override
	public void paint (Graphics g)
	{
		g.setColor( Color.black );
		g.fillRect( 0, 0, width, height );
		g.setColor( Color.green );
	    
		drawScreenBasic(g, x, y);
	}
	
	/**
	 * Draws the basic screen frame, corner lines and inner square
	 * @param x X position of the user
	 * @param y Y position of the user
	 */
	private void drawScreenBasic( Graphics g, int x, int y ){
	
		// we don't want to go all the way to the edge of the screen
		double slope = 1.0 / ( innerRatio-1.0 );
		
		//shift coordinates so they're from the centre of the screen.
		x = x-width/2;
		y = y-height/2;
		
		//do calculation for how close to the edge we are
		x = (int)Math.round( slope * x );
		y = (int)Math.round( slope * y );

		//shift coordinates back
		x = x+width/2;
		y = y+height/2;
		
		// move the x and y coords, helps with drawing the middle rectangle and the line loops
		x = x-iWidth/2;
		y = y-iHeight/2;
		
		g.fillRect( x, y, iWidth, iHeight);
		
		//draw all the corner lines
		int c[][] =
				{
					{0,0} ,
					{1,0} , {2,0} , {3,0} ,
					{1,3} , {2,3} , {3,3} ,
					{0,1} , {0,2} , {0,3} ,
					{3,1} , {3,2} , {3,3} ,
					{3,3}
				};
		for( int i=0; i < c.length; i++ ){
			g.drawLine(
					width/3* c[i][0],
					height/3* c[i][1],
					x + iWidth/3*c[i][0],
					y + iHeight/3*c[i][1]
					);
		}
		
		System.out.println("Painted at: ("+x+","+y+")");
	}
	
	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyPressed(KeyEvent arg0) {
		int dir = 1;
		System.out.println( arg0.getKeyCode() );
		switch( arg0.getKeyCode() ){
			case 81:
			case 27:
				System.exit(0);
				break;
			case 65:
				dir = -1;
			case 69:
				x += moveSpeed*dir;
				break;
			case 44:
				dir = -1;
			case 79:
				y += moveSpeed*dir;
				break;
			case 32:
				System.out.println( getWidth() +" "+ getHeight() );
				break;
		}
		y = Math.min( height, Math.max(0, y) );
		x = Math.min( width, Math.max( 0, x) );
		repaint();
	}

	@Override
	public void keyReleased(KeyEvent arg0) {}

	@Override
	public void keyTyped(KeyEvent arg0) {}

}
